#!/usr/bin/env python
#-*- coding:utf-8 -*-

import sys
import logging
import simplejson as json

import kanboxsettings

from logging import handlers
from PySide import QtCore, QtGui

from kanbox.login import *
from kanbox.mainWindow import *

from oauth2.auth2_kb import *

chLevel = logging.DEBUG
fhLevel = logging.DEBUG

# Logger Settings
_logger = logging.getLogger('kanbox')
_logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(chLevel)
# create file handler and set loglevel
fh = logging.handlers.RotatingFileHandler('kanbox.log', maxBytes=10*1024*1024, backupCount=6)
fh.setLevel(fhLevel)

# create formatter
formatter = logging.Formatter('<%(asctime)s %(name)s %(levelname)s> %(message)s')

# add formatter to ch
ch.setFormatter(formatter)
fh.setFormatter(formatter)

# add ch to logger
_logger.addHandler(ch)
_logger.addHandler(fh)

#import urllib2

#from oauth2client.client import OAuth2WebServerFlow

#flow = OAuth2WebServerFlow(client_id='7ce7a9e9435566dbb30f04bbc6b83d12',
#                           client_secret='0a998eb5d8411c3c206425bac2a5d48c',
#                           auth_uri = 'https://auth.kanbox.com/0/auth',
#                           scope='',
#                           redirect_uri='urn:ietf:wg:oauth:2.0:oob')
                           

#print flow

#auth_uri = flow.step1_get_authorize_url()

#print auth_uri

#req = urllib2.Request(auth_uri)
#response = urllib2.urlopen(req)
#print response.read()

auth2 = auth2KB()

if __name__ == '__main__':
    #Load setting file
    with open('config', 'r') as f:
        #print f.read()
        kanboxsettings.Settings = json.load(f)    
        #print kbSettings['RootPath']
    # show login window    
    app = QtGui.QApplication(sys.argv)
    win = Login(auth2=auth2)
    win.show()
    if win.exec_() == QtGui.QDialog.Accepted:
        win = MainWin(auth2=auth2)
        win.show()
        sys.exit(app.exec_())
    else:
        sys.exit(-1)
